package com.xvwang.blog.servlet;

import com.xvwang.blog.model.User;
import com.xvwang.blog.service.ArticleService;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/article.html")
public class ArticleServlet extends HttpServlet  {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String aidStr = req.getParameter("aid");
        if (aidStr == null){
            resp.sendError(400,"请使用正确的文章id");
            return;
        }
        int aid;
        try {
            aid = Integer.parseInt(aidStr);
        } catch (NumberFormatException exc) {
            resp.sendError(400,"请输入正确的文章id");
            return;
        }

        User user = null;
        HttpSession session = req.getSession(false);
        if(session != null){
            user = (User)session.getAttribute("currentUser");

        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();

        if(user == null){
            //说明用户没有登录
            writer.printf("<p>你还没有登录，点击<a href='/login.html'>此处</a>登录</p>\r\n");
            return;
        }

        Map<String,Object> articleData = ArticleService.getArticleData(user,aid);
        if(articleData == null){
            resp.sendError(404,"文章对应的id不存在");
            return;
        }

        ServletContext servletContext = req.getServletContext();
        WebContext webContext = new WebContext(req,resp,servletContext);
        webContext.setVariable("user",user);

        webContext.setVariables(articleData);

        TemplateEngine engine =(TemplateEngine) servletContext.getAttribute("engine");
        String body = engine.process("article",webContext);
        //写入正文
        writer.println(body);


    }
}
